﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Schema;
using FineUICore;
using AliyunOss;
using Kalman;
using Microsoft.AspNetCore.Diagnostics;

namespace AdminUI
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureDatabase();
            services.AddDistributedMemoryCache();
            services.AddSession();
            services.AddSingleton<AliyunOssClient>();//注册阿里云OSS客户端SDK

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                options.LoginPath = new PathString("/Login");
                options.Cookie.HttpOnly = true;
            });

            // 配置请求参数限制
            services.Configure<FormOptions>(x =>
            {
                x.ValueCountLimit = 1024;   // 请求参数的个数限制（默认值：1024）
                x.ValueLengthLimit = 4194304;   // 单个请求参数值的长度限制（默认值：4M, 4194304 = 1024 * 1024 * 4）
            });

            services.AddCors(c =>
            {
                c.AddPolicy("AllRequests", policy =>
                {
                    policy.SetIsOriginAllowed(_ => true)
                    //.AllowAnyOrigin()
                    //.WithOrigins(new string[] { "https://mmbiz.qpic.cn" })
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();

                });
            });

            // FineUI 服务
            services.AddFineUI(Configuration);

            services.AddRazorPages().AddMvcOptions(options =>
            {
                // 自定义模型绑定（Newtonsoft.Json）
                options.ModelBinderProviders.Insert(0, new JsonModelBinderProvider());

                // 自定义 WebForms 过滤器（仅在启用 EnableWebForms 时有效）
                options.Filters.Insert(0, new FineUICore.WebFormsFilter());
            }).AddNewtonsoftJson().AddRazorRuntimeCompilation();

            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = null; ////数据格式按原样输出，不会自动转为驼峰命名
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                //app.UseExceptionHandler(config =>
                //{
                //    config.Run(async context =>
                //    {
                //        context.Response.StatusCode = 500;
                //        context.Response.ContentType = "application/json";

                //        var error = context.Features.Get<IExceptionHandlerFeature>();
                //        if (error != null)
                //        {
                //            var ex = error.Error;
                //            await context.Response.WriteAsync(new ErrorModel
                //            {
                //                StatusCode = 500,
                //                ErrorMessage = ex.Message
                //            }.ToString());
                //        }
                //    });
                //});

                app.UseDeveloperExceptionPage();
                //app.UseExceptionHandler("/Error");
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();   
            app.UseSession();

            app.UseRouting();

            //开启Cors跨域请求中间件
            app.UseCors("AllRequests");
            //app.UseMiddleware<CorsMiddleware>();

            app.UseAuthentication();
            app.UseAuthorization();

            // FineUI 中间件（确保 UseFineUI 位于 UseEndpoints 的前面）
            app.UseFineUI();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });

            ServiceLocator.Instance.Register(app.ApplicationServices);
            ServiceLocator.Instance.Register(env);
        }

        private class ErrorModel
        {
            public int StatusCode { get; set; }
            public string ErrorMessage { get; set; }
        }
    }
}
